<!DOCTYPE html>
<?php
session_start();
?>
<html>
<?php
    
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minates ago
    session_unset();     // unset $_SESSION variable for the runtime 
    session_destroy();   // destroy session data in storage
    
    $host  = $_SERVER['HTTP_HOST'];
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $extra = 'index.php';
    header("Location: http://$host$uri/$extra?expire=true");
    exit;
    }
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>    
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Botany Dichotomous Key Conversion System</title>
        <link rel="stylesheet" type="text/css" href="css/default.css" />
        <link rel="stylesheet" type="text/css" href="css/stepsMenu.css" />
        
    </head>
    <body>
        <?php                    
            $uploaddir= $_POST["output"];
            $inputFile = $uploaddir."keyconversion.xml";
            //echo "The file is ". $inputFile;
            $xml = simplexml_load_file($inputFile);
            $sxe = new SimpleXMLElement($xml->asXML());
            //This is the directory where images will be saved 
            $target = "images/"; 
            //$target = $target . basename( $_FILES['photo']['name']);
            
            // Get the no. of glossary terms added 
            $glossaryItemsCount = $_POST["glossaryItemsCount"];
            if($glossaryItemsCount== ""){
                 $glossaryItemsCount = 0;
            }
            //echo "glossaryItemsCount = ".$glossaryItemsCount."<br />";
            /***************/
            if($glossaryItemsCount > 0){
                unset($sxe->GlossaryItems[0]->GlossaryItem);
            }
            /*****************/
            //Add all <GlossaryItem> elements
            for($x = 0; $x < $glossaryItemsCount; $x++){
                $glossaryItemsNode = $sxe->GlossaryItems[0];
                $glossaryItemsNode->addChild("GlossaryItem");
            }
            
            //Add <itemID>, <title>, <description> and <itemImage> for each glossary Item 
            for($i = 0; $i < $glossaryItemsCount; $i++){
                $imagecount=1;
                $glossaryItem = $glossaryItemsNode->GlossaryItem[$i];
                
                //if(!empty ($_POST["$glossaryTitle"])){
                    $glossaryTitle = "glossaryTitle".($i+1);
                    if(!empty ($_POST["$glossaryTitle"])){
                    $glossaryItem->addChild("itemID", ($i+1));

                    //$glossaryTitle = "glossaryTitle".($i+1);
                    $glossaryItem->addChild("title", $_POST["$glossaryTitle"]);

                    $glossaryDescription = "glossaryDescription".($i+1);
                    $glossaryItem->addChild("description", $_POST["$glossaryDescription"]);

                    $glossaryImage = "glossaryImage".($i+1);
                    $filename = "glossary" . ($i+1) . $imagecount . ".png";
                    $imagecount++;

                    if(!empty($_FILES["$glossaryImage"]["tmp_name"]))
                    {

                        $imgFileType = $_FILES["$glossaryImage"]["type"]; // The type of file it is
                        $imgFileTmpLoc = $_FILES["$glossaryImage"]["tmp_name"]; // File in the PHP tmp folder
                        $splitName = explode(".", $_FILES["$glossaryImage"]["name"]); // Split file name into an array using the dot
                        $imgFileExt = end($splitName); // Now target the last array element to get the file extension

                            //Check if uploaded image is in .png format, if not then convert
                            if (strtolower($imgFileExt) != "png") {
                                //echo "Uploaded image is not in .PNG format <br />";
                                //echo "file extension:". $imgFileExt."<br />";
                                //echo "target file: ".$imgFileTmpLoc."<br />";
                                $new_png = $uploaddir .$filename;
                                //echo "new png img: ".$new_png."<br />";
                                $ext = strtolower($imgFileExt);
                                $new_img = "";
                                if ($ext == "gif"){ 
                                    $new_img = imagecreatefromgif($imgFileTmpLoc);
                                } else if($ext =="jpg"){ 
                                    $new_img = imagecreatefromjpeg($imgFileTmpLoc);
                                }//else if($ext =="bmp"){
                                   // $new_img = imagecreatefrombmp($imgFileTmpLoc);
                                //}
                                imagepng($new_img, $new_png);
                                $glossaryItem->addChild("itemImage", "$filename");
                                imagedestroy($imgFileTmpLoc);
                             }
                            else{
                                //echo "Uploaded image is in .PNG format <br />";
                            //Upload  image file
                            move_uploaded_file($_FILES["$glossaryImage"]["tmp_name"], $uploaddir.$filename);
                            $glossaryItem->addChild("itemImage", "$filename");
                            }
                    }
                    else {
                        $glossaryItem->addChild("itemImage");     
                    }
                }
                
                // FOR PROPER FORMATTING XML
                // Create a new DOMDocument object
                $dom = new DOMDocument('1.0');
                // add spaces, new lines and make the XML more readable format        
                $dom->preserveWhiteSpace = false;
                $dom->formatOutput = true;
                //Load XML document from a string
                $dom->loadXML($sxe->asXML());
                //Save XML to file 
                $dom->save($inputFile);
            }
        
                    //Zip the directory
                    $zip = new ZipArchive;
                    $filename="./upload/KeyConversion".time().".zip";
                    $allfiles = $uploaddir."*";
                    if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
                        echo("cannot open <$filename>\n");
                    }
                    foreach (glob($allfiles) as $file) {
                        $zip->addFile($file);
                    }
                    $zip->close();
                    /* remove directory */
                   /* foreach(glob($uploaddir . '/*') as $file) {
                        if(is_dir($file))
                            rrmdir($file);  
                        else
                            unlink($file);
                    }
                    rmdir($uploaddir);*/
         ?>

        <?php include("includes/header.php"); ?>
	<div id="page-wrap2">
            <div id="main-content">
                <div id="left-col">
                    <?php include("includes/menuConfirm.php"); ?>
                </div><!-- end of left-col -->
                
                <div id = "right-col">
                    <h3>Download .zip File</h3>
                    <!--<form action="success.php" method="post" enctype="multipart/form-data"> -->
                        <fieldset id="confirmField">
                          <form action="<?php echo $filename?>" method="post">
                              <p class="instruction">Please click following button and select "Save File" option to download the output .ZIP file.
                              </p>
                              <input type="submit" class="download" value="Download .ZIP File"/> <br /><br />
                            <a href="index.php" >Back to main page</a>
                        </fieldset>
                   <!-- </form>    -->
                </div><!-- end of right-col -->

                <div class="clear"></div> <!-- all the content inside main-content div element is floated, need to clear float...
                                              because height of main-content does not know how tall it would be -->

            </div><!-- end of main-content -->        
        </div>  <!-- End of page-wrap -->                    
        <?php include("includes/footer.php"); ?>
                
    </body>
</html> 
